//
//  WLVideoVController.m
//  WanLian
//
//  Created by muzhuang on 2018/10/12.
//  Copyright © 2018年 wanlian. All rights reserved.
//

#import "WLVideoVController.h"
#import "WLVideoAudioCell.h"
#import "WLCloudFileModel.h"
#import "WLCloudMoreView.h"
#import "WLFileRenameAlertView.h"
#import "WLCloudDetailVController.h"
#import "WLDeleteAlertView.h"
#import "UIScrollView+EmptyDataSet.h"
#import "WLFileHandle.h"
#import "NSString+Ext.h"
#import "WLDownLoadCenter.h"
#import "WLFileUpDownLoadModel.h"
#import "WLVideoPlayManager.h"
#import "WLUpLoadCenter.h"

@interface WLVideoVController ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>

@property (nonatomic, strong) NSMutableArray *arrVideos;
@property (nonatomic, assign) NSInteger pageVideo;
@property (nonatomic, strong) UITableView *tbVideo;
@property (nonatomic, strong) WLCloudFileModel *selectedModel;
@property (nonatomic, strong) WLVideoPlayManager *player;

@end

@implementation WLVideoVController
- (void)receiveUploadSuccessNofication:(NSNotification *)notifi {
    [self reqCloudPhoto];
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kUploadSuccessNofication object:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveUploadSuccessNofication:) name:kUploadSuccessNofication object:nil];
    WLWkSelf
    _arrVideos = [[NSMutableArray alloc] init];
    _pageVideo = 1;
    _tbVideo = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _tbVideo.backgroundColor = wlBackColor;
    _tbVideo.delegate = self;
    _tbVideo.dataSource = self;
    _tbVideo.rowHeight = WLScaleX(68);
    _tbVideo.tableFooterView = [UIView new];
    if (@available(iOS 11.0, *)) {
        _tbVideo.estimatedSectionHeaderHeight = 0;
    }
    [self.view addSubview:_tbVideo];
    [_tbVideo mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(weakSelf.view);
    }];
    _tbVideo.mj_header = [WLFreshGifHeader headerWithRefreshingBlock:^{
        weakSelf.tbVideo.mj_footer = nil;
        //        [weakSelf.arrVideos removeAllObjects];
        weakSelf.pageVideo = 1;
        [weakSelf reqCloudPhoto];
    }];
    
    self.tbVideo.emptyDataSetSource = self;
    self.tbVideo.emptyDataSetDelegate = self;
    
    [weakSelf reqCloudPhoto];
    
}

- (void)addVideoFooterRefresh
{
    WLWkSelf
    _tbVideo.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [weakSelf reqCloudPhoto];
    }];
}

-(void)reqCloudPhoto
{
    WLWkSelf
//    NSDictionary *conditions = @{@"fileType":@0};
//    NSDictionary *pages = @{@"page":@(_pageVideo),@"num":@10};
//    NSDictionary *params = @{@"conditions":conditions,@"page":pages};
//    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"storage/item/type" withParamsDic:params success:^(NSDictionary *successDict) {
//    NSString *url = [WLCommonTool getRealURLWithUrlStr:@"/cgi-bin/luci/file/upload/list?fileType=0"];
    
    NSString *url = nil;
    if ([WLCommonTool isConnectedTianYiLian]) {
        url = [NSString stringWithFormat:@"%@/cgi-bin/luci/file/upload/list?fileType=0", HTTP_HOST_ROUTER];
    } else {//http://router.skywindlink.com/router/storage/item/type/0/c12478fa924e3371283f2b9a0bfc921a
        url = [NSString stringWithFormat:@"%@/storage/item/type/0/%@", HTTP_HOST_WEB,[[WLUseManager shareUser] getUserCurrentRouter]];
    }
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:url withParamsDic:nil success:^(NSDictionary *successDict) {
        __strong __typeof(weakSelf) strongSelf = weakSelf;
        [strongSelf.tbVideo.mj_header endRefreshing];
        NSInteger productCount = [successDict[@"object"] count];
        if (strongSelf.pageVideo==1)
        {
            [strongSelf.arrVideos removeAllObjects];
            if (productCount>10)
            {
                [strongSelf addVideoFooterRefresh];
            }
        }
        NSArray *arrPros = [WLCloudFileModel mj_objectArrayWithKeyValuesArray:successDict[@"object"]];
        
        arrPros = [self filterUploadingArrWithArray:arrPros];
        if (arrPros.count>0) {
            [strongSelf.arrVideos addObjectsFromArray:arrPros];
            if (strongSelf.arrVideos.count >= productCount) {
                [strongSelf.tbVideo.mj_footer endRefreshingWithNoMoreData];
            }
            else
            {
                [strongSelf.tbVideo.mj_footer endRefreshing];
            }
            //            [strongSelf.tbRouter reloadData];
        }
        else
        {
            [strongSelf.tbVideo.mj_footer endRefreshingWithNoMoreData];
        }
        [strongSelf.tbVideo reloadData];
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        [weakSelf showHUDMessage:errorMsg];
        [weakSelf celarData];
        [weakSelf.tbVideo.mj_header endRefreshing];
        [weakSelf.tbVideo.mj_footer endRefreshing];
    } error:^(NSError *error) {
        [weakSelf celarData];
        [weakSelf.tbVideo.mj_header endRefreshing];
        [weakSelf.tbVideo.mj_footer endRefreshing];
    } inView:self.view];
}
- (void)celarData {
    [self.arrVideos removeAllObjects];
    [self.tbVideo reloadData];
}
- (NSArray *)filterUploadingArrWithArray:(NSArray *)arr {
    NSMutableArray *res = [NSMutableArray array];
    WLUpLoadCenter *center = [WLUpLoadCenter shareInstance];
    for (WLPhotoSubModel *subModel in arr) {
        if (![center judgeInUploadingWithFileName:subModel.fileName]) {
            [res addObject:subModel];
        }
    }
    return res;
}

#pragma mark - UITableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arrVideos.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *strPhoto = @"photoCell";
    WLVideoAudioCell *cell = [tableView dequeueReusableCellWithIdentifier:strPhoto];
    if (!cell) {
        cell = [[WLVideoAudioCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strPhoto];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    WLCloudFileModel *fileModel = self.arrVideos[indexPath.row];
//    NSString *url = [WLCommonTool getRealURLWithUrlStr:fileModel.filePath];
//    UIImage *image = [WLFileHandle thumbnailImageForVideo:[NSURL URLWithString:url] atTime:1.f];
    cell.ivHead.image = [UIImage imageNamed:@"video_placeholder"];
//    [cell.ivHead sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:nil];
    cell.labName.text = fileModel.fileName;
    NSString *formateSize = [NSString formateSizeWithKBytes:(unsigned long long)[fileModel.fileSize longLongValue]];
    NSString *date = [NSString timestampSwitchTime:fileModel.uploadTime andFormatter:@"yyyy/MM/dd HH:mm"];
    cell.labSize.text = [NSString stringWithFormat:@"%@  %@",formateSize,date];
    
    cell.btnMore.tag = indexPath.row;
    [cell.btnMore addTarget:self action:@selector(moreInfoAction:) forControlEvents:UIControlEventTouchUpInside];
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
//    WLCloudFileModel *fileModel = self.arrVideos[indexPath.row];
//    self.player = [[WLVideoPlayManager alloc] init];
//    self.player.currentController = self;
//    [self.player openmovieWithVideoURL:[WLCommonTool getRealURLWithUrlStr:fileModel.filePath]];
    
    
}
- (void)moreInfoAction:(UIButton *)moreBtn
{
    self.selectedModel = self.arrVideos[moreBtn.tag];
    WLWkSelf
    [WLCloudMoreView showMoreViewTitle:_selectedModel.fileName action:^(NSInteger index) {
        if (index==0) {
            [weakSelf videoDownload];
        }
        else if (index==1)
        {
            [self deletePhotoAction];
        }
        else if (index==2)
        {
            [self renameAction];
        }
        else if (index==3)
        {
            WLCloudDetailVController *detailController = [[WLCloudDetailVController alloc] init];
//            detailController.fileID = weakSelf.selectedModel.fileId;
            detailController.fileModel = self.selectedModel;
            [weakSelf.navigationController pushViewController:detailController animated:YES];
        }
    }];
}

- (void)videoDownload
{
    [self addTaskToCenterWihtModel:self.selectedModel];
}
- (void)addTaskToCenterWihtModel:(WLCloudFileModel *)selectModel {
    
    WLFileUpDownLoadModel *model = [[WLFileUpDownLoadModel alloc] init];
    model.requestURL = selectModel.filePath;
    model.fileType = SPFileTypeVideo;
    model.loadState = FileLoadingStateWaiting;
    model.fileName = selectModel.fileName;
    model.fileTotalBytes = [selectModel.fileSize longLongValue] * KB_UNIT;
    model.isUpLoad = NO;
    model.saveToAbulm = YES;
    model.showInCompleteList = YES;
    NSArray *tasksArr = @[model];
    [[WLDownLoadCenter shareInstance] addTasks:tasksArr];
    [[NSNotificationCenter defaultCenter] postNotificationName:kUpDownloadTaskCompleteNofication object:nil];
}

- (void)deletePhotoAction
{
    WLWkSelf
    WLDeleteAlertView *bindingView = [[WLDeleteAlertView alloc] initWithTitle:_selectedModel.fileName];
    bindingView.okAction = ^{
        [weakSelf deletePhoto];
    };
    [bindingView show];
}

- (void)deletePhoto
{
    WLWkSelf
//    NSString *url = [NSString stringWithFormat:@"/cgi-bin/luci/file/upload/deleteitem?filePath=%@", self.selectedModel.srcFilePath];
    
    NSString *url = nil;
    if ([WLCommonTool isConnectedTianYiLian]) {
        url = [NSString stringWithFormat:@"%@/cgi-bin/luci/file/upload/deleteitem?filePath=%@", HTTP_HOST_ROUTER, self.selectedModel.srcFilePath];
    } else {//https://www.zeerong.com/router/web/storage/item/delete?key=c12478fa924e3371283f2b9a0bfc921a&filepath=/mnt/mmcblk0p1/photo/1.jpg
        url = [NSString stringWithFormat:@"%@/storage/item/delete?key=%@&filepath=%@", HTTP_HOST_WEB,[[WLUseManager shareUser] getUserCurrentRouter], self.selectedModel.srcFilePath];
    }
    
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:url withParamsDic:nil success:^(NSDictionary *successDict) {
        [weakSelf showHUDMessage:successDict[@"message"]];
        [self.arrVideos removeObject:self.selectedModel];
        [weakSelf.tbVideo reloadData];
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        [weakSelf showHUDMessage:errorMsg];
    } error:^(NSError *error) {
        
    } inView:self.view];
}

- (void)renameAction
{
    WLWkSelf
    WLFileRenameAlertView *bindingView = [[WLFileRenameAlertView alloc] initWithTitle:@"重命名文件"];
    bindingView.okAction = ^(NSString * _Nonnull strAddr) {
        [weakSelf renameFile:strAddr];
    };
    [bindingView setOriginContent:[self.selectedModel.fileName filterExtension]];
    [bindingView show];
}

- (void)renameFile:(NSString *)strName
{
    
    NSString *originNameSuffix = self.selectedModel.fileName.pathExtension;
    strName = [NSString stringWithFormat:@"%@.%@", strName, originNameSuffix];
    WLFileUpDownLoadModel *model = [[WLDownLoadCenter shareInstance] findTaskModelWithName:self.selectedModel.fileName];
    if (model.loadState == FileLoadingStateRunning) {
        [SVProgressHUD showAndAutoCloseWithStatus:@"文件正在下载中，不能修改名称" delayTime:2.f];
        return;
    }
    WLWkSelf
    NSString *url = nil;
    if ([WLCommonTool isConnectedTianYiLian]) {
        url = [NSString stringWithFormat:@"%@/cgi-bin/luci/file/upload/renameitem?srcFilePath=%@&dstFilePath=%@%@", HTTP_HOST_ROUTER, self.selectedModel.srcFilePath, self.selectedModel.relatePath, strName];
    } else {//https://www.zeerong.com/router/web/storage/item/delete?key=c12478fa924e3371283f2b9a0bfc921a&src=/mnt/mmcblk0p1/photo/1.jpg&dst=/mnt/mmcblk0p1/photo/2.jpg
        url = [NSString stringWithFormat:@"%@/storage/item/rename?key=%@&src=%@&dst=%@%@",HTTP_HOST_WEB, [[WLUseManager shareUser] getUserCurrentRouter], self.selectedModel.srcFilePath, self.selectedModel.relatePath, strName];
    }
//    NSString *urlStr = [NSString stringWithFormat:@"/cgi-bin/luci/file/upload/renameitem?srcFilePath=%@&dstFilePath=%@%@", self.selectedModel.srcFilePath, self.selectedModel.relatePath, strName];
//    urlStr = [WLCommonTool getRealURLWithUrlStr:urlStr];
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:url withParamsDic:nil success:^(NSDictionary *successDict) {
        NSString *newFilePath = [weakSelf.selectedModel.filePath stringByReplacingOccurrencesOfString:weakSelf.selectedModel.fileName withString:strName];
        weakSelf.selectedModel.filePath = newFilePath;
        
        WLFileUpDownLoadModel *model = [[[WLDownLoadCenter shareInstance] queryModelWithFileName:weakSelf.selectedModel.fileName] firstObject];
        if (model) {
            model.fileName = strName;
            
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            if (model.bg_createTime.length > 0) {
                [dict setObject:model.bg_createTime forKey:@"bg_createTime"];
            }
            [[WLDownLoadCenter shareInstance] updateTaskToDataBaseWithModel:model condictionDict:dict];
        }
        weakSelf.selectedModel.fileName = strName;
        [weakSelf.tbVideo reloadData];
        [weakSelf showHUDMessage:@"修改成功"];
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        [weakSelf showHUDMessage:errorMsg];
    } error:^(NSError *error) {
        
    } inView:self.view];
}


#pragma mark - DZNEmpty
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"no_photo"];
}

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *title = @"还没有上传视频哦~";
    NSDictionary *attributes = @{
                                 NSFontAttributeName:[WLCommonTool fontTypePingFangSCRegular:17],
                                 NSForegroundColorAttributeName:wlDarkGrayColor
                                 };
    return [[NSAttributedString alloc] initWithString:title attributes:attributes];
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
{
    return YES;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
